package com.lizongbo.seotijian.web.servlets;

import java.io.IOException;
import java.util.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lizongbo.seotijian.web.servlets.cgi.Cgi;
import com.lizongbo.seotijian.web.servlets.cgi.GooglePRCgi;
import com.lizongbo.seotijian.web.servlets.cgi.WhoisCgi;

/**
 * 
 * 处理http://seotijian.com/cgi-bin/*的请求
 * 
 * @author lizongbo
 * 
 */
public class CGIServlet extends javax.servlet.http.HttpServlet {
	Map<String, Cgi> cgiMap = null;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		cgiMap = new HashMap<String, Cgi>();
		this.addCgi(new WhoisCgi());
		this.addCgi(new GooglePRCgi());
	}

	private void addCgi(Cgi cgi) {
		cgiMap.put(cgi.getCgiName(), cgi);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// 解析url,拆出 handler的名字，拆出后面的参数，再拆出输出内容要的格式
		String uri = req.getRequestURI();
		String prefix = req.getContextPath() + req.getServletPath();
		System.out.println("cgi uri=" + uri);
		System.out.println("cgi url=" + req.getRequestURL());
		System.out.println("prefix=" + prefix);
		uri = trimRepeatSlash(uri);
		System.out.println("cgi url=" + uri);
		System.out.println("cgi servlet=" + req.getServletPath());
		if (uri.startsWith(prefix)) {
			String cgi = uri.substring(prefix.length());
			cgi = cgi.replace("//", "/");
			System.out.println("cgi=========" + cgi);
			while (cgi.startsWith("/")) {
				cgi = cgi.substring(1);
			}
			System.out.println("cgi aaa=========" + cgi);
			if (cgi.indexOf("/") > 0) {
				String cgiName = cgi.substring(0, cgi.indexOf("/"));
				String param = cgi.substring(cgi.indexOf("/") + 1);
				System.out.println("cgiName==" + cgiName);
				System.out.println("param===" + param);
				for (String key : cgiMap.keySet()) {
					if (cgiName.equalsIgnoreCase(key)) {
						cgiMap.get(key).doCgi(cgiName, param, req, resp);
					}
				}
			}
		}

	}

	/**
	 * 清除多余的斜线字符
	 * 
	 * @param s
	 * @return
	 */
	public static String trimRepeatSlash(String s) {
		StringBuilder sb = new StringBuilder(s.length());
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (i > 1 && c == '/') {
				if (c != s.charAt(i - 1) || s.charAt(i - 2) == ':') {
					sb.append(c);
				}
			} else {
				sb.append(c);
			}
		}
		return sb.toString();

	}
}
